<template>
  <div class="labor-checkin">
    <!-- 新增选项卡 -->
    <div class="activity-tabs">
      <el-radio-group v-model="activeTab" size="large">
        <el-radio-button label="participated">我参与的</el-radio-button>
        <el-radio-button label="published">我发布的</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 我参与的内容（使用真实数据） -->
    <div v-if="activeTab === 'participated'" class="checkin-layout">
      <!-- 左侧打卡卡片区域 -->
      <div class="left-panel">
        <div class="cards-container">
          <labor-card
              v-for="activity in dailyStatusData"
              :key="activity.activityId"
              :title="activity.title"
              :start-date="activity.startDate"
              :end-date="activity.endDate"
              :checked="activity.isChecked"
              :total-days="activity.totalDays"
              :checked-days="getCheckedDays(activity.activityId)"
              @check="handleCheck(activity)"
          />
        </div>
      </div>

      <!-- 右侧区域 -->
      <div class="right-panel">
        <calendar-view
            @date-selected="handleDateSelected"
        />
        <timeline-view
            :items="timelineItems"
            class="timeline-section"
        />
      </div>
    </div>

    <!-- 我发布的内容（暂时置空） -->
    <div v-else class="empty-published">
      <el-empty description="暂无发布的活动" />
    </div>

    <!-- 新增：打卡弹窗 -->
    <checkin-dialog
        v-model:visible="checkinDialogVisible"
        :activity-id="selectedActivityId"
        :activity-title="selectedActivityTitle"
        @success="handleCheckinSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import LaborCard from './LaborCard.vue';
import CalendarView from './CalendarView.vue';
import TimelineView from './TimelineView.vue';
import CheckinDialog from './CheckinDialog.vue'; // 新增导入
import { activitiesByDate, statusByDate } from "@/api/teacher.ts";

// 新增选项卡状态
const activeTab = ref('participated');

// 响应式数据
const dailyStatusData = ref([]); // 每日活动状态数据
const activitiesDetailData = ref([]); // 活动详情数据
const selectedDate = ref(''); // 当前选中的日期

// 新增：弹窗相关状态
const checkinDialogVisible = ref(false);
const selectedActivityId = ref(0);
const selectedActivityTitle = ref('');

// 计算已打卡日期（从活动详情数据中提取）
const checkedDates = computed(() => {
  const dates = new Set();
  activitiesDetailData.value.forEach(activity => {
    if (activity.records && activity.records.length > 0) {
      activity.records.forEach(record => {
        dates.add(record.checkDate);
      });
    }
  });
  return Array.from(dates);
});

// 获取活动的已打卡天数（从活动详情数据中获取）
const getCheckedDays = (activityId: number) => {
  const activity = activitiesDetailData.value.find(a => a.activityId === activityId);
  return activity ? activity.checkedDays : 0;
};

// 时间轴数据（从活动详情数据转换）
const timelineItems = computed(() => {
  const items = [];
  activitiesDetailData.value.forEach(activity => {
    if (activity.records && activity.records.length > 0) {
      activity.records.forEach(record => {
        items.push({
          date: record.checkDate,
          time: record.checkTime,
          activity: activity.title,
          description: record.description,
          images: record.images || []
        });
      });
    }
  });

  // 按日期和时间排序
  return items.sort((a, b) => {
    const dateCompare = new Date(b.date).getTime() - new Date(a.date).getTime();
    if (dateCompare !== 0) return dateCompare;
    return b.time.localeCompare(a.time);
  });
});

// 处理日期选择
const handleDateSelected = async (date: string) => {
  selectedDate.value = date;

  try {
    // 获取每日活动状态
    const statusRes = await statusByDate(date);
    if (statusRes.success) {
      dailyStatusData.value = statusRes.data;
      console.log('每日活动状态:', statusRes.data);
    } else {
      console.error('获取活动状态失败:', statusRes.message);
    }
  } catch (error) {
    console.error('加载活动状态失败:', error);
  }

  try {
    // 获取活动详情
    const activitiesRes = await activitiesByDate(date);
    if (activitiesRes.success) {
      activitiesDetailData.value = activitiesRes.data;
      console.log('活动详情:', activitiesRes.data);
    } else {
      console.error('获取活动详情失败:', activitiesRes.message);
    }
  } catch (error) {
    console.error('加载活动详情失败:', error);
  }
};

// 修改：处理打卡操作 - 现在接收整个activity对象
const handleCheck = (activity: any) => {
  if (activity.isChecked) {
    console.log(`活动 "${activity.title}" 已打卡，无需重复打卡`);
    return;
  }

  // 设置选中活动的信息
  selectedActivityId.value = activity.activityId;
  selectedActivityTitle.value = activity.title;

  // 打开打卡弹窗
  checkinDialogVisible.value = true;
  console.log(`打开活动 "${activity.title}" 的打卡弹窗`);
};

// 新增：处理打卡成功回调
const handleCheckinSuccess = () => {
  console.log('打卡成功，重新加载数据');
  // 重新加载当前日期的数据
  handleDateSelected(selectedDate.value);
};

// 组件挂载时加载今天的数据
onMounted(() => {
  const today = new Date().toISOString().split('T')[0];
  handleDateSelected(today);
});
</script>

<style scoped>
.labor-checkin {
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 新增选项卡样式 */
.activity-tabs {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

/* 我发布的内容空状态 */
.empty-published {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 保持原有样式不变 */
.checkin-layout {
  display: flex;
  height: calc(100% - 40px);
  gap: 20px;
}

.left-panel, .right-panel {
  flex: 1;
  min-width: 0;
}

.cards-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.right-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.timeline-section {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08);
}

/* 响应式设计 */
@media (max-width: 992px) {
  .checkin-layout {
    flex-direction: column;
  }

  .cards-container {
    grid-template-columns: 1fr;
  }
}
</style>
